import os.path
from werkzeug.security import  generate_password_hash
from flask import Blueprint,render_template,jsonify,request,send_from_directory,session,make_response
from models import BookInfoModel,BookModel,UserModel,OrderModel,AdminModel,OrderItemModel
from exts import db
# from .utility import ImageCode
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from io import BytesIO

import random
import base64

bp = Blueprint("admin", __name__, url_prefix="/admin")

# 管理员首页
@bp.route("/")
def index():
    user=session.get('admin')
    return render_template("Admin/index.html",user=user)

# 欢迎页面
@bp.route("/welcome")
def welcome():
    return render_template("Admin/admin/welcome.html")

# 图书列表页面
@bp.route("/booklist")
def booklist():
    return render_template("Admin/book/bookList.html")

# 图书添加页面
@bp.route("/book/add")
def bookAdd():
    return render_template("Admin/book/bookAdd.html")

# 订单列表页面
@bp.route("/orderList")
def orderList():
    return render_template("Admin/order/orderList.html")

# 用户列表页面
@bp.route("/userlist")
def userlist():
    return render_template("Admin/user/userList.html")

# 查询所有书籍
@bp.route("/querybook")
def querybook():
    # 查询参数
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    bookname=request.args.get('bookname',default='%',type=str)
    booksort = request.args.get('booksort', default='%', type=str)
    bookauthor = request.args.get('bookauthor', default='%', type=str)
    startprice = request.args.get('startprice', default=0, type=int)
    endprice = request.args.get('endprice', default=1000, type=int)
    list = []
    content = {}
    books=BookModel.query.join(BookInfoModel).filter(BookModel.bookid==BookInfoModel.bookid,BookModel.bookname.like(f'%{bookname}%'),BookModel.booksort.like(f'%{booksort}%'),
          BookInfoModel.bookauthor.like(f'%{bookauthor}%'),BookInfoModel.bookprice>=startprice,BookInfoModel.bookprice<=endprice)
    count = BookModel.query.join(BookInfoModel).filter(BookModel.bookid==BookInfoModel.bookid,BookModel.bookname.like(f'%{bookname}%'),BookModel.booksort.like(f'%{booksort}%'),
          BookInfoModel.bookauthor.like(f'%{bookauthor}%'),BookInfoModel.bookprice>=startprice,BookInfoModel.bookprice<=endprice).count()
    page_book = books.paginate(
        page=int(page),
        per_page=int(limit),
        error_out=False,
        max_per_page=50,
    ).items
    for book in page_book:
        content={'bookid':book.bookid,'bookname':book.bookname,'booksort':book.booksort,'bookauthor':book.bookinfo.bookauthor,
                 'bookdinfo':book.bookinfo.bookdinfo,'bookprice':book.bookinfo.bookprice}
        list.append(content)
        content={}
    print(list) # 查询结果
    return jsonify({'code':'0','message': 'success', 'data':list, 'count':count})

# 图片上传
@bp.route("/uploadImg",methods=['POST'])
def uploadImg():
    global filename
    file=request.files['file']
    if file:
        filename=file.filename
        print(filename)
        file.save(os.path.join('static/image/detail',filename)) # 图片存储在static/image目录下
    return jsonify({'code':'0','filename':filename})

# 添加图书
@bp.route("/addbook")
def addbook():
    # 图书信息
    bookid=request.args.get('bookid')
    bookname=request.args.get('bookname')
    booksort = request.args.get('booksort')
    bookauthor = request.args.get('bookauthor')
    bookprice = request.args.get('bookprice')
    bookdinfo = request.args.get('bookdinfo')
    pngname=request.args.get('pngname')
    print(pngname)
    url = bookname + '.png'
    print(url)
    book=BookModel.query.filter_by(bookid=bookid).first()
    if book:
        return jsonify({'state':'400','message':"图书编号已存在！"})
    else:
        books = BookModel(bookid=bookid, bookname=bookname, booksort=booksort)
        db.session.add(books)
        db.session.commit()
        bookinfo = BookInfoModel(bookid=bookid, bookauthor=bookauthor, bookdinfo=bookdinfo, bookprice=bookprice,bookbinfo="1")
        db.session.add(bookinfo)
        db.session.commit()
        old_path=os.path.join('static/image/detail',pngname)
        new_path=os.path.join('static/image/detail',url)
        os.rename(old_path,new_path)
        return jsonify({'state':'200','message':'添加成功！'})

# 跳转修改图书页面
@bp.route("/book/find/<bookid>")
def editbook(bookid):
    books = BookModel.query.filter(BookModel.bookid==bookid).first()
    print(books.bookid)
    print(books.bookinfo.bookauthor)
    return render_template("Admin/book/bookEdit.html",books=books)

# 修改图书
@bp.route("/book/edit")
def editBooks():
    # 要修改图书的内容
    bookid = request.args.get('bookid')
    bookname = request.args.get('bookname')
    booksort = request.args.get('booksort')
    bookauthor = request.args.get('bookauthor')
    bookprice = request.args.get('bookprice')
    bookdinfo = request.args.get('bookdinfo')
    pngname = request.args.get('pngname')
    url = bookname + '.png'
    deleteurl="static/image/detail/"+bookname+".png"
    try:
        os.remove(deleteurl)
        print("删除成功")
    except:
        print("删除失败")
    book = BookModel.query.filter_by(bookid=bookid).first()
    book.booksort=booksort
    book.bookinfo.bookauthor=bookauthor
    book.bookinfo.bookprice=bookprice
    book.bookinfo.bookdinfo=bookdinfo
    db.session.commit()
    old_path = os.path.join('static/image/detail', pngname)
    new_path = os.path.join('static/image/detail', url)
    os.rename(old_path, new_path)
    return jsonify({'state': '200', 'message': '修改成功！'})

# 删除某本图书
@bp.route("/deleteBook/<bookid>")
def deleteBook(bookid):
    print(bookid)
    book = BookModel.query.filter_by(bookid=bookid).first()
    bookname=book.bookname
    db.session.delete(book)
    db.session.commit()
    deleteurl = "static/image/detail/" + bookname + ".png"
    try:
        os.remove(deleteurl)
        print("删除成功")
    except:
        print("删除失败")
    return jsonify({'state':'200','message':'删除成功！'})

# 删除多本图书
@bp.route("/deleteBooks/<bookid>")
def deleteBooks(bookid):
    print(bookid)
    lst = list(map(str, bookid.split(',')))
    book = db.session.query(BookModel).filter(BookModel.bookid.in_(lst))
    for a in book:
        deleteurl = "static/image/detail/" + a.bookname + ".png"
        try:
            os.remove(deleteurl)
            print("删除成功")
        except:
            print("删除失败")
    db.session.query(BookInfoModel).filter(BookInfoModel.bookid.in_(lst)).delete(synchronize_session=False)
    db.session.query(BookModel).filter(BookModel.bookid.in_(lst)).delete(synchronize_session=False)
    db.session.commit()
    return jsonify({'state': '200', 'message': '删除成功！'})

# 查询所有用户信息
@bp.route("/user/searchAll")
def searchAllUser():
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    list = []
    content = {}
    user=UserModel.query
    count=UserModel.query.count()
    page_user = user.paginate(
        page=int(page),
        per_page=int(limit),
        error_out=False,
        max_per_page=50,
    ).items
    for u in page_user:
        content={'userid':u.userid,'username':u.username,'userpassword':generate_password_hash(u.userpassword),'useremail':u.useremail,
                 'userphone':u.userphone}
        list.append(content)
        content={}
    print(list)
    return jsonify({'code': '0', 'message': 'success', 'data': list, 'count': count})

# 查询所有订单信息
@bp.route("/orders")
def orders():
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    list = []
    content = {}
    orders=OrderModel.query
    count = OrderModel.query.count()
    page_order = orders.paginate(
        page=int(page),
        per_page=int(limit),
        error_out=False,
        max_per_page=50,
    ).items
    for u in page_order:
        content={'oid':u.oid,'uid':u.uid,'recv_name':u.recv_name,'recv_phone':u.recv_phone,'status':u.status,
                 'recv_address':u.recv_province+" "+u.recv_city+" "+u.recv_area+" "+u.recv_address,'total_price':u.total_price,'order_time':u.order_time.strftime('%Y-%m-%d %H:%M:%S')}
        list.append(content)
        content={}
    print(list)
    return jsonify({'code': '0', 'message': 'success', 'data': list, 'count': count})

# 验证码图片
def rand_color():
    red = random.randint(32, 200)
    green = random.randint(22, 255)
    blue = random.randint(0, 200)
    return red, green, blue

# 生成4位验证码
def validate_picture():
    total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789'
    # 图片大小130 x 50
    width = 120
    heighth = 40
    # 先生成一个新图片对象
    im = Image.new('RGB', (width, heighth), 'white')
    # 设置字体
    font = ImageFont.truetype(font='arial.ttf', size=30)
    # 创建draw对象
    draw = ImageDraw.Draw(im)
    str = ''
    # 输出每一个文字
    for item in range(4):
        text = random.choice(total)
        str += text
        draw.text((-3 + random.randint(3, 7) + 25 * item, -3 + random.randint(2, 7)), text=text, fill=rand_color(),font=font)
    # 划几根干扰线
    for num in range(1):
        x1 = random.randint(0, width / 2)
        y1 = random.randint(0, heighth / 2)
        x2 = random.randint(0, width)
        y2 = random.randint(heighth / 2, heighth)
        draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
    return im, str

# 返回验证码
@bp.route("/vcode")
def vcode():
    image,code=validate_picture()
    buf = BytesIO()
    image.save(buf, 'jpeg')
    response = make_response(buf.getvalue())
    response.headers['Content-Type'] = 'image/jpeg'
    session['vcode'] = code
    return response

# 登录页面
@bp.route("/login")
def adminlogin():
    # data = run_code()  # 生成新验证码
    return render_template("Admin/login.html")

# 管理员登录
@bp.route("/user/login")
def userlogin():
    users=request.args.get('username')
    password=request.args.get('password')
    captcha=request.args.get('captcha')
    print(password)
    user=AdminModel.query.filter_by(username=users).first()
    if user:
        if user.password==password:
            if session.get('vcode').lower()==captcha.lower():
                session['admin']=users
                return jsonify({'state':'200','msg':'正确！'})
            else:
                return jsonify({'state': '400', 'msg': '验证码错误！'})
        else:
            return jsonify({'state': '400', 'msg': '密码错误！'})
    else:
        return jsonify({'state':'400','msg':'用户不存在！'})

# 个人信息页面
@bp.route("/info")
def info():
    username=session.get('admin')
    user=AdminModel.query.filter_by(username=username).first()
    return render_template("Admin/admin/info.html",user=user)

# 修改密码页面
@bp.route("/password")
def password():
    return render_template("Admin/admin/password.html")

# 编辑信息
@bp.route("/edit")
def edit():
    # 要修改的内容
    username=request.args.get('username')
    phone = request.args.get('phone')
    email = request.args.get('email')
    remark = request.args.get('remark')
    user = AdminModel.query.filter_by(username=username).first()
    user.phone=phone
    user.email=email
    user.remark=remark
    db.session.commit()
    return jsonify({'state':'200','message':'修改成功！'})

# 修改密码
@bp.route("/password/update")
def password_update():
    password=request.args.get('password')
    username=session.get('admin')
    user = AdminModel.query.filter_by(username=username).first()
    user.password=password
    db.session.commit()
    return jsonify({'state':'200','message':'修改成功！'})

# 删除用户
@bp.route("/user/delete/<id>")
def deleteuser(id):
    print(id)
    user=UserModel.query.filter_by(userid=id).first()
    db.session.delete(user)
    db.session.commit()
    return jsonify({'state':'200','message':'删除用户成功！'})

# 修改订单信息页面
@bp.route("/order/change/<id>")
def orderchange(id):
    print(id)
    order = OrderModel.query.filter_by(oid=id).first()
    content = {'oid': order.oid, 'uid': order.uid, 'recv_name': order.recv_name, 'recv_phone': order.recv_phone,'recv_province': order.recv_province, 'recv_city': order.recv_city,
               'recv_area': order.recv_area, 'recv_address': order.recv_address, 'total_price': order.total_price,'order_time': order.order_time, 'status': order.status}
    books=OrderItemModel.query.filter_by(oid=id).all()
    list=[]
    content1={}
    for book in books:
        bookname=book.title.split('-')[0]+".png"
        content1={'title':book.title,'price':book.price,'num':book.num,'bookname':bookname}
        list.append(content1)
    print(list)
    return render_template("Admin/order/orderEdit.html",order=content,books=list)

# 修改订单状态
@bp.route("/changestatus")
def changestatus():
    oid=request.args.get('oid')
    status=request.args.get('booksort')
    print(oid)
    print(status)
    order = OrderModel.query.filter_by(oid=oid).first()
    order.status=status
    db.session.commit()
    return jsonify({'state':'200','message':'修改成功！'})

# 图表统计页面
@bp.route("/echarts")
def echarts():
    # 统计每个类别书的个数
    wcount=db.session.query(BookModel).filter_by(booksort='文学').count()
    lcount=db.session.query(BookModel).filter_by(booksort='历史').count()
    kcount=db.session.query(BookModel).filter_by(booksort='科幻经典').count()
    zcount=db.session.query(BookModel).filter_by(booksort='专业书').count()
    count=[wcount,lcount,kcount,zcount]
    return render_template("Admin/admin/echarts.html",count=count)